﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Windows.Media;

namespace Algoritmos_de_Ordenação.Algoritmos
{
    public class QuickSort : DrawingRegion
    {
        public QuickSort()
        {
        }
        
        public QuickSort(TabItem tabItem)
            : base(tabItem, TabType.Quick)
        {
        }
        int comparisons = 0;
        int swaps = 0;
        protected override void DoSort()
        {

            comparisons = 0;
            swaps = 0;
            sorted = false;
            
            DoQuickSort(0, numElemArray - 1);

            endSorting(comparisons, swaps);
        }


        private void DoQuickSort(int p, int r)
        {
            if (p < r)
            {
                int q = partition(p, r);
                
                DoQuickSort(p, q - 1);//6
                
                DoQuickSort(q + 1, r);//7
            }
        }

        private int partition(int p, int r)
        {
            int x = numberArray[r];
            int i = p - 1;
            updateGBThread(15);
            for (int j = p; j <= r - 1; j++)//16
            {
                wf();
                comparisons++;
                compareTwoThread(r, j);
                updateInformationsThread(SortStatus.Sorting, comparisons, swaps);
                updateGBThread(17);
                if (numberArray[j] <= x)//18
                {
                    i++;
                    swaps++;
                    wf();
                    swapTwoThread(j, i);
                    updateGBThread(18);
                    updateInformationsThread(SortStatus.Sorting, comparisons, swaps);
                    int temp = numberArray[i];
                    numberArray[i] = numberArray[j];//19
                    numberArray[j] = temp;
                }
            }
            compareTwoThread(r, i + 1);
            updateGBThread(21);
            wf();
            swaps++;
            swapTwoThread(r, i + 1);
            
            updateInformationsThread(SortStatus.Sorting, comparisons, swaps);

            int tempFora = numberArray[i + 1];
            numberArray[i + 1] = numberArray[r];//22
            numberArray[r] = tempFora;

            return i + 1;
        }
    }
}

